package contract

import (
	"context"
	"raymond/global"
	"runtime"

	"github.com/ethereum/go-ethereum/accounts"
	"github.com/ethereum/go-ethereum/accounts/abi/bind"
	"github.com/ethereum/go-ethereum/accounts/keystore"
	"github.com/ethereum/go-ethereum/crypto"
)

var passphrase string = "yym@home2013"

const keystorePath_mac string = "/Users/raymond/blockworks/dev/geth-dev/keystore"
const keystorePath_win string = "D:/works/geth-dev/keystore"

func GetKeystorePath() string {
	switch runtime.GOOS {
	case "darwin":
		return keystorePath_mac
	case "windows":
		return keystorePath_win
	}
	return keystorePath_win
}

func NewAuthByKeystore(acctIdx uint) (*bind.TransactOpts, error) {
	client := global.Client()
	ks := keystore.NewKeyStore(GetKeystorePath(), keystore.StandardScryptN, keystore.StandardScryptP)
	//am := accounts.NewManager(&accounts.Config{InsecureUnlockAllowed: false}, ks)
	var acct accounts.Account
	accts := ks.Accounts()
	if len(accts) == 0 {
		acct0, err := ks.NewAccount(passphrase)
		if err != nil {
			return nil, err
		}
		acct = acct0
	} else {
		acct = accts[acctIdx]
	}
	if acctIdx == 0 {
		passphrase = ""
	}
	err := ks.Unlock(accts[acctIdx], passphrase)
	if err != nil {
		return nil, err
	}
	chainID, err := client.NetworkID(context.Background())
	if err != nil {
		return nil, err
	}
	// 对账户解锁授权其进行部署

	auth, err := bind.NewKeyStoreTransactorWithChainID(ks, acct, chainID)
	if err != nil {
		return nil, err
	}
	return auth, nil
}

func NewAuthByPrivatekey(pr string) (*bind.TransactOpts, error) {
	client := global.Client()
	privateKey, err := crypto.HexToECDSA(pr)
	if err != nil {
		return nil, err
	}
	chainID, err := client.NetworkID(context.Background())
	if err != nil {
		return nil, err
	}
	auth, err := bind.NewKeyedTransactorWithChainID(privateKey, chainID)
	if err != nil {
		return nil, err
	}
	return auth, nil
}
